package com.jzo2o.health.listener;

import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.enums.OrderStatusEnum;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.model.domain.OrdersCancelled;
import com.jzo2o.health.service.OrdersCancelledService;
import com.jzo2o.health.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersCancelledService ordersCancelledService;
    @Autowired
    private ApplicationContext applicationContext;
    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_TRADE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        Orders orders = ordersService.getById(msg);
        if (ObjectUtils.isNull(orders)){
            throw new CommonException("订单不存在");
        }
        if (orders.getOrderStatus().equals(OrderStatusEnum.NO_PAY.getStatus())){
            OrdersCancelled ordersCancelled = ordersCancelledService.getById(orders.getId());
            if (ObjectUtils.isNotEmpty(ordersCancelled)){
                throw new CommonException("订单已取消,不能重复取消");
            }
            OrdersCancelled ordersCancelled1 = new OrdersCancelled();
            ordersCancelled1.setCancellerType(4);
            ordersCancelled1.setId(orders.getId());
            ordersCancelled1.setCancelReason("超时系统自动取消");
            ordersCancelled1.setCancelTime(LocalDate.now());
            TradeStatusListener bean = applicationContext.getBean(TradeStatusListener.class);
            bean.OverTimePayOrderForCancel(ordersCancelled1);
        }
        log.info("接收到支付结果状态的消息 ({})-> {}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);
    }

    @Transactional(rollbackFor = Exception.class)
    public void OverTimePayOrderForCancel(OrdersCancelled ordersCancelled){
        boolean save = ordersCancelledService.save(ordersCancelled);
        if (!save){
            throw new DBException("操作失败");
        }
        boolean update = ordersService.lambdaUpdate().set(Orders::getOrderStatus, OrderStatusEnum.CANCELLED.getStatus()).update();
        if (!update){
            throw new DBException("操作失败");
        }
    }
}
